package com.main.rentsystem.controller.user;

import com.main.rentsystem.pojo.entity.Message;
import com.main.rentsystem.pojo.entity.Result;
import com.main.rentsystem.pojo.entity.User;
import com.main.rentsystem.pojo.vo.MessageVO;
import com.main.rentsystem.service.UserServer;
import com.main.rentsystem.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController()
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServer userServer;

    public static Long USER_ID;

    @GetMapping("/login")
    public Result login(User userx) {
        log.info("用户登录");
        User user = userServer.login(userx);
        if(user != null) {
            USER_ID = user.getId();
            //自定义信息
            Map<String , Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username",user.getUsername());
            claims.put("password",user.getPassword());
            //使用JWT工具类，生成身份令牌
            String token = JwtUtils.generateJwt(claims);
            return Result.success(token);
        }
        return Result.error("error");
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        log.info("用户注册");
        if(userServer.isExist(user) != null){
            return Result.error("exist");
        }
        userServer.register(user);
        return Result.success();
    }

    @GetMapping("/changePassword/{oldPassword}/{newPassword}")
    public Result changePassword(@PathVariable("oldPassword") String oldPassword,  @PathVariable("newPassword")String newPassword) {
        log.info("原密码{},新密码{}",oldPassword,newPassword);
        User user = userServer.getUserById(USER_ID);
        if(user != null && user.getPassword().equals(oldPassword)){
            userServer.changePassword(user,newPassword);
            return Result.success();
        }
        return Result.error("error");
    }

    @PostMapping("/message")
    public Result userMessage(@RequestBody Message message){
        log.info("用户评价：{}",message.getContent());
        userServer.PutMessage(message);
        return Result.success();
    }

    @GetMapping("/getMessage")
    public Result GetMessage(){
        log.info("查询我的留言");
        User user = new User();
        user.setId(USER_ID);
        List<MessageVO> messageVOList = userServer.GetMessage(user);
        return Result.success(messageVOList);
    }

}
